<?php
require_once ("../utils/ConnectionFactory.php");
require_once ("../persistance/data/DetailDO.php");

/**
 * CRUD pour detailDO
 * @author Quentin LAUJAC, Charles Hurtevent
 *
 */
class DetailDAO{

	/**
	 * retourne la liste des detailDO par numero de commande
	 * @param entier $numeroCommande
	 */
	public function getListDetailDOByNumCommande($numeroCommande){

		$connection = ConnectionFactory::getConnection ();
		$reponse = $connection->query ( "SELECT * FROM detail WHERE num_cde = ".$numeroCommande);
		if ($reponse == null || $reponse->rowCount () == 0) {
			return null;
		}

		$listDetailDO = new ArrayObject ();
		while ( $donnee = $reponse->fetch () ) {
			$detailDO = $this->setDetailDO ( $donnee );
			$listDetailDO->append ( $detailDO );
		}
		return $listDetailDO;

	}
	/**
	 * Insert une liste de DetailDO dans la base
	 * @param ArrayObject $listDetailDO
	 */
	public function insertListDetailDO(ArrayObject $listDetailDO){
		$connection = ConnectionFactory::getConnection ();

		foreach($listDetailDO as $detailDO){
			echo "<br/>numCommande = ".$detailDO->getNumeroCommande();
			echo "<br/>numArticle = ".$detailDO->getNumeroArticle();
			echo "<br/>Quantite = ".$detailDO->getQuantiteCommande();
			$req = $connection->prepare("INSERT INTO detail(num_cde, num_art, qte_commandee) VALUES (:num_cde, :num_art, :qte_commandee)");
			$req->execute(array(
			'num_cde' => $detailDO->getNumeroCommande(),
			'num_art' => $detailDO->getNumeroArticle(),
			'qte_commandee' => $detailDO->getQuantiteCommande()
			));
		}

		//print_r($req->errorInfo());
	}

	/**
	 * Met a jour la liste de DetailDO en base
	 * @param unknown_type $listDetailDO
	 */
	public function updateListDetailDO(ArrayObject $listDetailDO){
		$connection = ConnectionFactory::getConnection ();

		foreach($listDetailDO as $detailDO){
			$req = $connection->prepare("UPDATE detail SET qte_commandee = :qte_commandee WHERE num_cde = :num_cde AND num_art = :num_art");
			$req->execute(array(
			'num_cde' => $detailDO->getNumeroCommande(),
			'num_art' => $detailDO->getNumeroArticle(),
			'qte_commandee' => $detailDO->getQuantiteCommande()
			));
		}
	}

	public function deleteListDetailDO(ArrayObject $listDetailDO){
		$connection = ConnectionFactory::getConnection ();

		foreach($listDetailDO as $detailDO){
			$req = $connection->prepare("DELETE FROM detail WHERE num_cde = :num_cde AND num_art = :num_art");
			$req->execute(array(
			'num_cde' => $detailDO->getNumeroCommande(),
			'num_art' => $detailDO->getNumeroArticle(),
			));
		}
	}

	private function setDetailDO($donnee){
		$detailDO = new DetailDO();
		$detailDO->setNumeroArticle($donnee['num_art']);
		$detailDO->setNumeroCommande($donnee['num_cde']);
		$detailDO->setQuantiteCommandee($donnee['qte_commandee']);

		return $detailDO;
	}
}